package com.imooc.sell.service.impl;


import com.imooc.sell.VO.pan.*;
import com.imooc.sell.dao.OrderMasterDao;
import com.imooc.sell.dataobject.OrderMaster;
import com.imooc.sell.utils.pyhutils.RemarkResultUtils;

import com.imooc.sell.dao.RemarkDao;
import com.imooc.sell.dataobject.Remark;
import com.imooc.sell.service.RemarkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ModelAttribute;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 评论业务实现类
 */
@Service
public class RemarkServiceImpl implements RemarkService {

    @Autowired /*自动装入*/
    @SuppressWarnings("all")
    private RemarkDao remarkDao;

    /**
     * 查询所有评论信息
     *
     * @return 返回一个自定义封装结果类
     */
    @Override
    public RemarkResult getAll() {
        try {
            return RemarkResultUtils.success(remarkDao.findAll());
        } catch (Exception e) {
            e.printStackTrace();
            return RemarkResultUtils.error();
        }
    }

    /**
     * 后台查询所有评论的接口
     *
     * @return RemarkRemark封装类
     */
    @Override
    public RemarkRemark getAllAdmin() {
        try {
            RemarkRemark remarkRemark = new RemarkRemark(1, "成功", remarkDao.findAll());
            return remarkRemark;
        } catch (Exception e) {
            e.printStackTrace();
            return new RemarkRemark();
        }
    }

    /**
     * 查询全部数据封装成一个List<HashMap<String,RVO2>>返回
     *
     * @param page 页数
     * @param size 长度
     * @param pArr page数组
     * @return List<HashMap   <   String   ,   RVO2>>
     */
    @Override
    @SuppressWarnings("all")
    public List<HashMap<String, RVO2>> getAllAdminPagable(Integer page, Integer size, Page[] pArr) {
        //获取数据库全部数据
        List<Remark> rl = remarkDao.findAll();
        //数据封装类
        RRM2 rrm = new RRM2(1, "成功", rl);
        //开始位置、结束位置、封装类长度
        int start = size * page;
        int end = size * page + size;
        int rrsize = rrm.getRemarkremarkmap().size();
        //切割数组
        List<HashMap<String, RVO2>> asr = new ArrayList<>();
        //切割
        if (end <= rrsize) {
            asr = rrm.getRemarkremarkmap().subList(start, end);
        } else {
            if (start < rrsize)
                asr = rrm.getRemarkremarkmap().subList(start, rrsize);
        }
        //计算总页数
        long l = (long) rrsize;
        Pageable pageable = new PageRequest(page, size);
        pArr[0] = new PageImpl(asr, pageable, l);
        return asr;
    }

    /**
     * 根据orderid查询所有的评论具体内容
     *
     * @return 返回值为一个list<Remark>列表
     */
    @Override
    public RemarkResult getAllRemarkById(String orderId) {
        try {
            if (orderId == null) {
                return RemarkResultUtils.error("订单id（orderId）未传");
            } else if (orderId.equals("")) {
                return RemarkResultUtils.error("订单id（orderId）为空字符串");
            } else
                return RemarkResultUtils.success(remarkDao.findByOrderId(orderId));
        } catch (Exception e) {
            if (e instanceof DataIntegrityViolationException) {
                return RemarkResultUtils.error("请检查是否完整传入所有参数");
            }
            e.printStackTrace();
            return RemarkResultUtils.error(e.getMessage());
        }
    }

    /**
     * 通过Id查询所有数据
     *
     * @param orderId 订单Id
     * @param page    页数
     * @param size    页大小
     * @param pArr    中间参数
     * @return 封装结果
     */
    @Override
    @SuppressWarnings("all")
    public List<HashMap<String, RVO2>> getAllRemarkByIdAdmin(String orderId, Integer page, Integer size, Page[] pArr) {
        //获取数据库全部数据
        List<Remark> rl = remarkDao.findByOrderId(orderId);
        //数据封装类
        RRM2 rrm = new RRM2(1, "成功", rl);
        //开始位置、结束位置、封装类长度
        int start = size * page;
        int end = size * page + size;
        int rrsize = rrm.getRemarkremarkmap().size();
        //切割数组
        List<HashMap<String, RVO2>> asr = new ArrayList<>();
        //切割
        if (end <= rrsize) {
            asr = rrm.getRemarkremarkmap().subList(start, end);
        } else {
            if (start >= rrsize) {

            } else
                asr = rrm.getRemarkremarkmap().subList(start, rrsize);
        }


        /*if (size*page+size<=rrm.getRemarkremarkmap().size()){
            asr =  rrm.getRemarkremarkmap().subList(start,end-1);
        }else {
            asr =  rrm.getRemarkremarkmap().subList(start,rrsize);
        }*/
        //计算总页数
        long l = rrsize;
        Pageable pageable = new PageRequest(page, size);
        pArr[0] = new PageImpl(asr, pageable, l);
        return asr;
    }

    /**
     * 通过时间范围查找相关评论数据
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param page      页数
     * @param size      一页大小
     * @param pArr      中间参数
     * @return 封装结果List<HashMap   <   String   ,       RVO2>>
     */
    @Override
    @SuppressWarnings("all")
    public List<HashMap<String, RVO2>> getAllRemarkByTimeScope(
            String startTime, String endTime, Integer page, Integer size, Page[] pArr) {
        //获取数据库全部数据
        List<Remark> rl = remarkDao.findAll();
        //获取时间范围内的数据
        RRM2 rrm2 = new RRM2(1, "成功", rl);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //List<Remark> rll = new ArrayList<>() ;
        List<HashMap<String, RVO2>> endresult = new ArrayList<>();
        try {
            Date st = sdf.parse(startTime);
            Date et = sdf.parse(endTime);
            for (HashMap hashMap : rrm2.getRemarkremarkmap()) {
                if ((!hashMap.get("user").equals("")) || hashMap.get("user") != null) {
                    RVO2 rvo2 = (RVO2) hashMap.get("user");
                    String time = rvo2.getUpdateTime();
                    Date date = sdf.parse(time);
                    if (st.before(date) && date.before(et)) {
                        endresult.add(hashMap);
                    }
                }
            }
            //数据封装类
            //RRM2 rrm = new RRM2(1,"成功",rll);
            //开始位置、结束位置、封装类长度
            int start = size * page;
            int end = size * page + size;
            int rrsize = endresult.size();
            //切割数组
            List<HashMap<String, RVO2>> asr = new ArrayList<>();
            //切割

            if (end <= rrsize) {
                asr = endresult.subList(start, end);
            } else {
                if (start < rrsize)
                    asr = endresult.subList(start, rrsize);
            }
            //计算总页数
            long l = (long) rrsize;
            Pageable pageable = new PageRequest(page, size);
            pArr[0] = new PageImpl(asr, pageable, l);

            return asr;
        } catch (ParseException e) {

            return null;
        }
    }

    @Override
    public Remark getRemarkByRemarkId(String remarkId) {
        return remarkDao.findByRemarkId(remarkId);
    }

    @SuppressWarnings("all")
    @Autowired
    OrderMasterDao orderMasterDao;

    /**
     * 添加一条评论
     * 参数为一个表的对应类，通过注解RequestBody，自动获取Json请求串当中的名字对应的参数
     *
     * @return 返回一个自定义封装类，RemarkResult2
     */
    @Override
    public RemarkResult2 addRemark(Remark addone) {
        try {
            if (addone.getOrderId() == null) {
                return RemarkResultUtils.error2("订单Id（orderId）未传入");
            } else if (addone.getOrderId().equals("")) {
                return RemarkResultUtils.error2("orderId为空字符串");
            } else {
                Remark r = remarkDao.save(addone);
                if (r.getRemarkId() != null) {
                    short i = 1;
                    OrderMaster orderMaster = orderMasterDao.getOne(addone.getOrderId());
                    orderMaster.setOrderStatus(i);
                    orderMasterDao.save(orderMaster);
                    return RemarkResultUtils.success2();
                } else
                    return RemarkResultUtils.error2("未知错误");
            }
        } catch (Exception e) {
            if (e instanceof DataIntegrityViolationException) {
                return RemarkResultUtils.error2("请检查是否完整传入所有参数");
            }
            e.printStackTrace();
            RemarkResultUtils.logger.error(e.getMessage());
            return RemarkResultUtils.error2(e.getMessage());
        }
    }

    @Override
    public RemarkResult2 addRemarkAdmin(@ModelAttribute("form") Remark addone) {
        try {
            if (addone.getOrderId() == null)
                return RemarkResultUtils.error2("订单号为空");
            else if (addone.getOrderId().equals("")) {
                return RemarkResultUtils.error2("订单号为空");
            } else {
                if (remarkDao.save(addone).getRemarkId() != null)
                    return RemarkResultUtils.success2();
                else
                    return RemarkResultUtils.error2("未知错误");
            }
        } catch (Exception e) {
            if (e instanceof DataIntegrityViolationException || e instanceof NullPointerException) {
                return RemarkResultUtils.error2("请检查是否完整传入所有参数");
            }
            e.printStackTrace();
            RemarkResultUtils.logger.error(e.getMessage());
            return RemarkResultUtils.error2(e.getMessage());
        }
    }

    /**
     * 更新一个评论信息
     *
     * @param remark 请求参数
     * @return 返回一个自定义封装类，RemarkResult2
     */
    @Override
    public RemarkResult2 updataRemark(Remark remark) {
        try {
            Remark isremark = remarkDao.findByRemarkId(remark.getRemarkId());
            isremark.setUpdateTime(null);
            isremark.setComment(remark.getComment());
            if (remark.getRemarkId() == null) {
                return RemarkResultUtils.error2("评论Id（remarkId）未传");
            } else if (remark.getRemarkId().equals("")) {
                return RemarkResultUtils.error2("评论Id（remarkId）为空字符串");
            } else if (remarkDao.save(isremark).getRemarkId() != null)
                return RemarkResultUtils.success2();
            else
                return RemarkResultUtils.error2();
        } catch (Exception e) {
            if (e instanceof DataIntegrityViolationException) {
                return RemarkResultUtils.error2("请检查是否完整传入所有参数");
            }
            if (e instanceof NullPointerException) {
                return RemarkResultUtils.error2("请检查是否完整且正确的传入所有参数");
            }
            RemarkResultUtils.logger.error(e.getMessage());
            return RemarkResultUtils.error2(e.getMessage());
        }
    }

    @Override
    public RemarkResult2 deleteRemark(String remarkId) {
        try {
            remarkDao.deleteById(remarkId);
            return RemarkResultUtils.success2();
        } catch (Exception e) {
            if (e instanceof EmptyResultDataAccessException)
                return RemarkResultUtils.success2();
            return RemarkResultUtils.error2(e.getMessage());
        }
    }
}
